package com.util.abstractAction;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import com.opensymphony.xwork2.ActionSupport;
import com.util.fileUpload.FileUploadProcessor;
import com.util.fileUpload.UploadFile;

public class AbstractAction  extends ActionSupport{
	
	private static final long serialVersionUID = 1172903142815744089L;
	
	 protected HttpServletResponse response;
	 
	 protected HttpServletRequest request;
	 
	@Autowired
	@Qualifier("defaultFileUpload")
    private FileUploadProcessor defaultFileUpload;
	
	@Autowired
	@Qualifier("mutileFileUpload")
    private FileUploadProcessor mutileFileUpload;
    
	 
	 public void init() {
	        this.request = ServletActionContext.getRequest();
	        this.response = ServletActionContext.getResponse();
	        
	    }

	 protected <T> void print(T obj) {
	        this.print(obj, "application/octet-stream;charset=utf-8");
	  }
	 
	 private <T> void print(T str, String contentType) {
	    	response = ServletActionContext.getResponse();
	        print(response, str.toString(), contentType);
	    }
	 
	 public static void print(HttpServletResponse response, String str, String contentType) {
			PrintWriter out = null;
			try {
				out = response.getWriter();
			} catch (IOException e) {
				e.printStackTrace();
			}
			response.setContentType(contentType);
			if (out != null) {
				out.print(str);
				out.close();
			}
		}
	 
	
	    
	    public String saveImageFile(File imageFile, String dir, String imageFileFileName,
	            int imageWith, int imageHeight) throws Exception {

	    	 this.request = ServletActionContext.getRequest();
	        UploadFile files = new UploadFile(imageFile, dir, imageFileFileName, imageWith,
	                imageHeight, request);

	        String path = defaultFileUpload.uploadOneFile(files);

	        return path;
	    }
	    
	    public List<String> saveMutilImageFile(File imageFile, String dir, String imageFileFileName,
	            int[] imageWith, int[] imageHeight) throws Exception {
	    	 this.request = ServletActionContext.getRequest();
	        UploadFile files = new UploadFile(imageFile, dir, imageFileFileName, imageHeight,
	                imageWith, request);
	        List<String> list = null;
	        try {
	            list = mutileFileUpload.uploadFile(files);
	        } catch (Exception e) {
	           
	        }
	        return list;
	    }
	    
	    
	    public String saveFile(File file, String dir, String fileFileName) throws Exception {

	        UploadFile files = new UploadFile(file, dir, fileFileName, request);

	        String path = defaultFileUpload.uploadOneFile(files);

	        return path;
	    }
}
